// 1.导入express
const express = require("express");
const bodyParser = require("body-parser");
//导入并配置cors中间件
const cors = require("cors");
const http = require("http");
const https = require("https");
var fs = require("fs");
var path = require("path");
var request = require("request");

const app = express();
const port = 8090;
const dirPath = path.join(__dirname, "/temp");
app.use(bodyParser.json());
app.use(cors());

// api 参数
let param = {};

// 测试 上传本地图片
const isTest = true;

// 保存cookie
let cookies = {};

//
const puppeteer = require("puppeteer");

/**
 * 测试环境地址
 * http://1.94.15.237:9003/user/login
 * jianing.sun
 * 123456
 *
 *
 * 正式环境地址
 * https://cssc-mgmt.csisolar.com/user/login
 * 17512544946
 * Hynhynhyn
 *
 */

// ------------------------方法区域------------------------

// 打开浏览器
const openBrowser = async () => {
  return new Promise(async (resolve, reject) => {
    // createDir();
    // 连接已打开的浏览器
    // let wsKey = await axios.get('http://localhost:21222/json/version');
    // const browser = await puppeteer.connect({
    //   browserWSEndpoint: wsKey.data.webSocketDebuggerUrl,
    //   defaultViewport: null,
    //   slowMo: 100,
    //   headless: true,
    //   timeout: 60000 * 5,
    // })

    // 打开新的浏览器
    const browser = await puppeteer.launch({
      // headless: true,
      headless: false,
      defaultViewport: {
        width: 1220,
        height: 1080,
      },
      slowMo: 100,
      args: [
        "--no-sandbox",
        "--disable-features=site-per-process",
        // "--start-maximized",
      ],
      timeout: 1000 * 60 * 3,
    });

    const page = await browser.newPage();
    await page.goto("http://1.94.15.237:9003/user/login");
    page.setDefaultTimeout(1000 * 60 * 3);
    const firstTabs = await page.waitForSelector(
      ".rootAnt-tabs-nav-wrap > div > div:nth-child(3)"
    );
    await firstTabs.click();

    // 账户和密码
    // const userName = await page.$("input[id='username']");
    // await userName.type("jianing.sun", { delay: 20 });

    // const inputIdEl = await page.$("input[id='pwd']");
    // await inputIdEl.type("123456", { delay: 20 });

    // 手机验证码
    const userName = await page.$("input[id='phone']");
    await userName.type("13815250740", { delay: 20 });

    const inputIdEl = await page.$("input[id='code']");
    await inputIdEl.type("de2ab1", { delay: 20 });

    const submitBtn = await page.$(".rootAnt-form > .rootAnt-btn");
    await submitBtn.click();

    const menu = await page.waitForSelector(
      ".rootAnt-menu > .rootAnt-menu-submenu div[title='户用金融系统']"
    );
    await menu.click();

    // 拿到cookies
    const cookies = await page.cookies();
    //cookies= [
    //   {
    //     name: 'CSI-TOKEN',
    //     value: 'e6cc0852a2144762a28cd1bc0f9e67d1',
    //     domain: '1.94.15.237',
    //     path: '/',
    //     expires: 1709780110.227034,
    //     size: 41,
    //     httpOnly: false,
    //     secure: false,
    //     session: false,
    //     sameParty: false,
    //     sourceScheme: 'NonSecure',
    //     sourcePort: 9003
    //   }
    // ]
    cookie = cookies[0];
    console.log(cookie);

    resolve({ browser, page });
  });
};

// 上传信息授权使用书
const ownerAuth = async ({ page, browser }) => {
  const ownerManage = await page.$(".rootAnt-menu > li[title='业主管理']");
  await ownerManage.click();

  const frame = await page.waitForFrame(frame => {
    if (frame.url().includes("micro-finance/finance/ownermanage")) {
      return frame;
    }
  });
  if (frame) {
    const ownermanagePage = await browser.newPage();
    ownermanagePage.setDefaultTimeout(1000 * 60 * 3);

    await ownermanagePage.goto(frame.url());

    const mobileNumber = await ownermanagePage.waitForSelector(
      "form input[id='mobileNumber']"
    );
    await mobileNumber.type(param.commonPhone, { delay: 20 });

    const queryBtn = await ownermanagePage.$(
      "form button.ant-btn.ant-btn-primary"
    );
    await queryBtn.click();

    await ownermanagePage.waitForResponse(
      response =>
        response.url().includes("api/finance-owner/external/owner/search") &&
        response.status() === 200
    );

    await ownermanagePage.waitForSelector(".ant-table-tbody .ant-space-item a");
    //
    await ownermanagePage.$$eval(
      ".ant-table-tbody .ant-space-item a",
      elements => {
        const a = elements.find(el => el.innerText == "编辑");
        a.click();
      }
    );

    let selector =
      "#root div > form:nth-child(3) > div > div.ant-card-body > div:nth-child(1) div.ant-col.ant-form-item-control > div.ant-form-item-control-input > div > span span";

    await ownermanagePage.waitForSelector(selector);

    const [fileChooser] = await Promise.all([
      ownermanagePage.waitForFileChooser(),
      ownermanagePage.click(selector),
    ]);

    await fileChooser.accept([
      "/Users/Hymn/Desktop/mywork/ats/src/temp/1707029912126.pdf",
    ]);

    //
    const responseData = await ownermanagePage.waitForResponse(
      response =>
        response.url().includes("api/upload/file/upload") &&
        response.status() === 200
    );
    const data = await responseData.json();
    sendAuthFileId(param.phone, data.data.id).then(() => {
      browser.close();
    });
    console.log(data.data.id, 444);
  }
};

// 业主信息补全
const ownerCompletion = async ({ page, browser }) => {
  // return
  readFile(__dirname + "/test.png")
    .then(data => {
      console.log(data);
      installUpload({ file: data, namespace: "finance" });
    })
    .catch(err => {
      console.log("err");
    });

  await getUrl(
    "https://resource.zhuyiyun.com/933175645864558595/aa18ab40-c3e3-11ee-aa3a-172d587a0a8f.jpg"
  );

  const ownerManage = await page.$(".rootAnt-menu > li[title='业主管理']");
  await ownerManage.click();

  const frame = await page.waitForFrame(frame => {
    if (frame.url().includes("micro-finance/finance/ownermanage")) {
      return frame;
    }
  });
  if (frame) {
    const ownermanagePage = await browser.newPage();
    ownermanagePage.setDefaultTimeout(1000 * 60 * 3);
    await ownermanagePage.goto(frame.url());

    const mobileNumber = await ownermanagePage.waitForSelector(
      "form input[id='mobileNumber']"
    );
    await mobileNumber.type(param.commonPhone, { delay: 20 });

    const queryBtn = await ownermanagePage.$(
      "form button.ant-btn.ant-btn-primary"
    );
    await queryBtn.click();

    await ownermanagePage.waitForResponse(
      response =>
        response.url().includes("api/finance-owner/external/owner/search") &&
        response.status() === 200
    );

    let aEl = await ownermanagePage.waitForSelector(
      ".ant-table-tbody .ant-space-item a"
    );
    console.log(aEl);
    //
    await ownermanagePage.$$eval(
      ".ant-table-tbody .ant-space-item a",
      elements => {
        const a = elements.find(el => el.innerText == "编辑");
        a.click();
      }
    );
    //
    await ownermanagePage.waitForSelector(
      "form:nth-child(2) > div.ant-space.ant-space-vertical > div:nth-child(4) > div > div.ant-card-body"
    );

    // 先删除
    await ownermanagePage.$$eval("button[title='删除文件']", buttonList => {
      buttonList.map(el => el.click());
    });

    let selectorList = [
      {
        name: "身份证人像",
        selector:
          "form:nth-child(2) .ant-card-body div.ant-col.ant-form-item-control > div.ant-form-item-control-input > div > span > div > div",
        key: "identityPortraitFile",
      },
      {
        name: "身份证国徽面",
        selector:
          "form:nth-child(2) .ant-card-body div:nth-child(2) div div.ant-form-item-control-input > div > span > div > div",
        key: "identityNationalFile",
      },
      {
        name: "银行卡",
        selector:
          "form:nth-child(2) .ant-card-body > div:nth-child(3) .ant-row.ant-form-item-row div.ant-form-item-control-input > div > span > div > div",
        key: "bankFile",
      },
      {
        name: "房产证明",
        selector:
          "form:nth-child(3) .ant-card-body > div:nth-child(1) .ant-col.ant-form-item-control .ant-form-item-control-input > div > span > div > div",
        key: "propertyOwnershipCertificateFile",
      },
    ];

    for (let index = 0; index < selectorList.length; index++) {
      await ownermanagePage.waitForSelector(selectorList[index].selector);

      let [fileChooser] = await Promise.all([
        ownermanagePage.waitForFileChooser(),
        ownermanagePage.click(selectorList[index].selector),
      ]);

      console.log(selectorList[index].name);

      let filePath =
        "/Users/Hymn/Desktop/mywork/ats/src/temp/1707029912126.pdf";
      await fileChooser.accept([filePath]);
    }

    const responseData = await ownermanagePage.waitForResponse(
      response =>
        response.url().includes("api/upload/file/upload") &&
        response.status() === 200
    );
    await responseData.json();
    const unameEl = ownermanagePage.$("input[id=uname]");
    await unameEl.type(param.phone);
    sendPhone(param.phone).then(res => {
      browser.close();
    });
    // console.log(data.data.id, 444);
  }
};

// 房屋信息 先点击派单 再点击执行
const house = async ({ page, browser }) => {
  const powerStation = await page.$(".rootAnt-menu div [title='电站管理']");
  await powerStation.click();

  const powerStationList = await page.$(
    ".rootAnt-menu > li[title='电站档案列表']"
  );
  await powerStationList.click();

  const frame = await page.waitForFrame(frame => {
    if (frame.url().includes("micro-finance/finance/powerStation/listAgency")) {
      return frame;
    }
  });
  if (frame) {
    const powerStationPage = await browser.newPage();
    powerStationPage.setDefaultTimeout(1000 * 60 * 3);

    await powerStationPage.goto(frame.url());

    const code = await powerStationPage.waitForSelector(
      "form input[id='code']"
    );
    await code.type(param.code, { delay: 20 });

    // 查询
    const queryBtn = await powerStationPage.$(
      "form button.ant-btn.ant-btn-primary"
    );
    await queryBtn.click();

    await powerStationPage.waitForResponse(
      response =>
        response
          .url()
          .includes("finance-owner/external/station/record/search") &&
        response.status() === 200
    );

    let AEl = await powerStationPage.waitForSelector(
      ".ant-table-wrapper table > tbody  div > a"
    );
    console.log(AEl, 111);
    //
    // await powerStationPage.$$eval(
    //   ".ant-table-wrapper table > tbody  div > a",
    //   elements => {
    //     const a = elements.find(el => el.innerText == "派单");
    //     if (a) {
    //       a.click();
    //     }
    //   }
    // );
    // const selectOption = await powerStationPage.waitForSelector(
    //   ".ant-modal-content input[id='userId']"
    // );
    // await selectOption.click();

    // const firstOption = await powerStationPage.waitForSelector(
    //   ".ant-select-dropdown .rc-virtual-list .ant-select-item"
    // );
    // await firstOption.click();

    // //
    // const ok = await powerStationPage.$(
    //   ".ant-modal-footer > button:nth-child(2)"
    // );
    // await ok.click();

    // // 查询
    // const queryAgain = await powerStationPage.$(
    //   "form button.ant-btn.ant-btn-primary"
    // );
    // await queryAgain.click();

    // await powerStationPage.waitForResponse(
    //   response =>
    //     response
    //       .url()
    //       .includes("finance-owner/external/station/record/search") &&
    //     response.status() === 200
    // );

    // AEl = await powerStationPage.waitForSelector(
    //   ".ant-table-tbody .ant-space-item a"
    // );
    // console.log(AEl, "ael11");
    //
    await powerStationPage.$$eval(
      ".ant-table-tbody .ant-space-item a",
      elements => {
        // 执行
        const a = elements.find(el => el.innerText == "执行");
        if (a) {
          a.click();
        }
      }
    );

    // 电站信息
    await powerStationPage.waitForSelector(".ant-tabs-tab > .ant-tabs-tab-btn");
    await powerStationPage.$$eval(
      ".ant-tabs-tab > .ant-tabs-tab-btn",
      elements => {
        const btn = elements.find(el => el.innerText == "电站信息");
        if (btn) {
          console.log(btn);
          btn.click();
        }
      }
    );

    // 房屋信息
    await powerStationPage.$$eval(
      ".ant-tabs-tab div.ant-tabs-tab-btn",
      elements => {
        const btn = elements.find(el => el.innerText == "房屋信息");
        if (btn) {
          btn.click();
        }
      }
    );

    await powerStationPage.waitForTimeout(2000);

    //
    const uploadList = await powerStationPage.$$(
      "form .ant-upload-list > .ant-upload"
    );
    for (let index = 0; index < uploadList.length; index++) {
      if (index != 5) {
        const element = await uploadList[index];

        const [fileChooser] = await Promise.all([
          powerStationPage.waitForFileChooser(),
          element.click(),
        ]);

        await fileChooser.accept([
          "/Users/Hymn/Desktop/mywork/ats/src/temp/1707029912126.pdf",
        ]);
        await powerStationPage.waitForTimeout(2000);
      }
    }
    //
    console.log(110);

    // const responseData = await powerStationPage.waitForResponse(response => {
    //   return response.status() == 200;
    // });
    // console.log(responseData.url(), 111);

    const saveEl = await powerStationPage.$(
      ".ant-pro-footer-bar .ant-pro-footer-bar-right div:nth-child(2) > button"
    );
    console.log(112);

    await saveEl.click();

    console.log(data.data.id, 444);
  }
};

// 设计信息
const design = async ({ page, browser }) => {
  const powerStation = await page.$(".rootAnt-menu div [title='电站管理']");
  await powerStation.click();

  const powerStationList = await page.$(
    ".rootAnt-menu > li[title='电站档案列表']"
  );
  await powerStationList.click();

  const frame = await page.waitForFrame(frame => {
    if (frame.url().includes("micro-finance/finance/powerStation/listAgency")) {
      return frame;
    }
  });
  if (frame) {
    const powerStationPage = await browser.newPage();
    powerStationPage.setDefaultTimeout(1000 * 60 * 3);

    await powerStationPage.goto(frame.url());

    const code = await powerStationPage.waitForSelector(
      "form input[id='code']"
    );
    await code.type(param.code, { delay: 20 });

    const queryBtn = await powerStationPage.$(
      "form button.ant-btn.ant-btn-primary"
    );
    await queryBtn.click();

    await powerStationPage.waitForResponse(
      response =>
        response
          .url()
          .includes("finance-owner/external/station/record/search") &&
        response.status() === 200
    );

    let AEl = await powerStationPage.waitForSelector(
      ".ant-table-tbody .ant-space-item a"
    );
    console.log(AEl);
    //
    await powerStationPage.$$eval(
      ".ant-table-tbody .ant-space-item a",
      elements => {
        const a = elements.find(el => el.innerText == "执行");
        a.click();
      }
    );
    // 电站信息
    await powerStationPage.waitForSelector(".ant-tabs-tab > .ant-tabs-tab-btn");
    await powerStationPage.$$eval(
      ".ant-tabs-tab div.ant-tabs-tab-btn",
      elements => {
        const btn = elements.find(el => el.innerText == "电站信息");
        if (btn) {
          btn.click();
        }
      }
    );

    // 设计信息
    await powerStationPage.$$eval(
      ".ant-tabs-tab div.ant-tabs-tab-btn",
      elements => {
        const btn = elements.find(el => el.innerText == "设计信息");
        btn.click();
      }
    );

    // 待上传元素
    const uploadList = await powerStationPage.$$(
      "form .ant-upload.ant-upload-select.ant-upload-select-text"
    );
    for (let index = 0; index < uploadList.length; index++) {
      if (index < 4) {
        const element = await uploadList[index];

        const [fileChooser] = await Promise.all([
          powerStationPage.waitForFileChooser(),
          element.click(),
        ]);

        await fileChooser.accept([
          "/Users/Hymn/Desktop/mywork/ats/src/temp/1707029912126.pdf",
        ]);
        await powerStationPage.waitForTimeout(2000);
      }
    }
    //
    console.log(110);

    //
    // const responseData = await powerStationPage.waitForResponse(
    //   response => response.status() == 200
    // );
    // const data = await responseData.json();
    // console.log(responseData.url(), 444);

    //
    await powerStationPage.$$eval(
      ".ant-tabs-tab div.ant-tabs-tab-btn",
      elements => {
        const btn = elements.find(el => el.innerText == "设备信息");
        if (btn) {
          btn.click();
        }
      }
    );
    const addBtn = await powerStationPage.waitForSelector(
      ".ant-pro-table-list-toolbar button"
    );
    let data = [
      { type: "组件", id: 93, number: 1 },
      { type: "逆变器", id: 93, number: 1 },
    ];
    for (let index = 0; index < data.length; index++) {
      await addBtn.click();
      // 点击类型下拉
      const typeInput = await powerStationPage.waitForSelector(
        ".ant-modal-body form input[id=type]"
      );
      await typeInput.click();

      const selectType = await powerStationPage.waitForSelector(
        `.rc-virtual-list div[label=${"组件"}]`
      );
      await selectType.click();

      // 点击类型下拉
      const modelInput = await powerStationPage.waitForSelector(
        ".ant-modal-body form input[id=model]"
      );
      await modelInput.click();

      const selectModel = await powerStationPage.waitForSelector(
        `.rc-virtual-list div[title="CS7N-MS(665W)"]`
      );
      await selectModel.click();
      // 数量
      const numberInput = await powerStationPage.waitForSelector(
        ".ant-modal-body form input[id=number]"
      );
      await numberInput.type("123131");

      // 确定
      const modalOk = await powerStationPage.$(
        ".ant-modal-content button:nth-child(2)"
      );
      await modalOk.click();
      // const element = array[index];
    }

    // const submitBtn = await powerStationPage.$(
    //   "main .ant-pro-footer-bar div:nth-child(3) > button"
    // );
    // await submitBtn.click();
  }
};

// 电站设备安装-执行
const install = async ({ page, browser }) => {
  const powerStation = await page.$(".rootAnt-menu div [title='电站管理']");
  await powerStation.click();

  const powerStationList = await page.$(
    ".rootAnt-menu > li[title='电站档案列表']"
  );
  await powerStationList.click();

  const frame = await page.waitForFrame(frame => {
    if (frame.url().includes("micro-finance/finance/powerStation/listAgency")) {
      return frame;
    }
  });
  if (frame) {
    const powerStationPage = await browser.newPage();
    powerStationPage.setDefaultTimeout(1000 * 60 * 3);

    await powerStationPage.goto(frame.url());

    const code = await powerStationPage.waitForSelector(
      "form input[id='code']"
    );
    await code.type(param.code, { delay: 20 });

    const queryBtn = await powerStationPage.$(
      "form button.ant-btn.ant-btn-primary"
    );
    await queryBtn.click();

    await powerStationPage.waitForResponse(
      response =>
        response
          .url()
          .includes("finance-owner/external/station/record/search") &&
        response.status() === 200
    );

    await powerStationPage.waitForSelector(
      ".ant-table-tbody .ant-space-item a"
    );

    await powerStationPage.$$eval(
      ".ant-table-wrapper table > tbody  div > a",
      elements => {
        const a = elements.find(el => el.innerText == "安装派单");
        if (a) {
          a.click();
        }
      }
    );
    const selectOption = await powerStationPage.waitForSelector(
      ".ant-modal-content input[id='user']"
    );
    await selectOption.click();

    const firstOption = await powerStationPage.waitForSelector(
      ".ant-select-dropdown .rc-virtual-list .ant-select-item"
    );
    await firstOption.click();

    //
    const ok = await powerStationPage.$(
      ".ant-modal-footer > button:nth-child(2)"
    );
    await ok.click();

    // 查询
    const queryAgain = await powerStationPage.$(
      "form button.ant-btn.ant-btn-primary"
    );
    await queryAgain.click();

    await powerStationPage.waitForResponse(
      response =>
        response
          .url()
          .includes("finance-owner/external/station/record/search") &&
        response.status() === 200
    );

    AEl = await powerStationPage.waitForSelector(
      ".ant-table-tbody .ant-space-item a"
    );
    console.log(AEl, "ael11");
    //
    await powerStationPage.$$eval(
      ".ant-table-tbody .ant-space-item a",
      elements => {
        const a = elements.find(el => el.innerText == "执行");
        a.click();
      }
    );

    // 安装信息
    await powerStationPage.waitForSelector(".ant-tabs-tab > .ant-tabs-tab-btn");
    await powerStationPage.$$eval(
      ".ant-tabs-tab div.ant-tabs-tab-btn",
      elements => {
        const btn = elements.find(el => el.innerText == "安装信息");
        btn.click();
      }
    );

    // 待上传元素
    const uploadList = await powerStationPage.$$("form span.ant-upload");

    for (let index = 0; index < uploadList.length; index++) {
      // if (index) {
      const element = await uploadList[index];

      const [fileChooser] = await Promise.all([
        powerStationPage.waitForFileChooser(),
        element.click(),
      ]);

      await fileChooser.accept([
        "/Users/Hymn/Desktop/mywork/ats/src/temp/1707029912126.pdf",
      ]);
      await powerStationPage.waitForTimeout(2000);
      // }
    }

    //
    // const responseData = await powerStationPage.waitForResponse(
    //   response =>
    //     response.url().includes("api/upload/file/upload") &&
    //     response.status() === 200
    // );
    // const data = await responseData.json();
    // console.log(data.data.id, 444);
  }
};

// 电站并网
const grid = async ({ page, browser }) => {
  const powerStation = await page.$(".rootAnt-menu div [title='电站管理']");
  await powerStation.click();

  const powerStationList = await page.$(
    ".rootAnt-menu > li[title='电站档案列表']"
  );
  await powerStationList.click();

  const frame = await page.waitForFrame(frame => {
    if (frame.url().includes("micro-finance/finance/powerStation/listAgency")) {
      return frame;
    }
  });
  if (frame) {
    const powerStationPage = await browser.newPage();
    powerStationPage.setDefaultTimeout(1000 * 60 * 3);

    await powerStationPage.goto(frame.url());

    const code = await powerStationPage.waitForSelector(
      "form input[id='code']"
    );
    await code.type(param.code, { delay: 20 });

    const queryBtn = await powerStationPage.$(
      "form button.ant-btn.ant-btn-primary"
    );
    await queryBtn.click();

    await powerStationPage.waitForResponse(
      response =>
        response
          .url()
          .includes("finance-owner/external/station/record/search") &&
        response.status() === 200
    );

    await powerStationPage.waitForSelector(
      ".ant-table-tbody .ant-space-item a"
    );
    //
    await powerStationPage.$$eval(
      ".ant-table-tbody .ant-space-item a",
      elements => {
        const a = elements.find(el => el.innerText == "详情");
        a.click();
      }
    );

    // 并网信息
    await powerStationPage.waitForSelector(".ant-tabs-tab > .ant-tabs-tab-btn");
    await powerStationPage.$$eval(
      ".ant-tabs-tab div.ant-tabs-tab-btn",
      elements => {
        const btn = elements.find(el => el.innerText == "并网信息");
        btn.click();
      }
    );

    let selector =
      "#root div > form:nth-child(3) > div > div.ant-card-body > div:nth-child(1) div.ant-col.ant-form-item-control > div.ant-form-item-control-input > div > span span";

    await powerStationPage.waitForSelector(selector);

    const [fileChooser] = await Promise.all([
      powerStationPage.waitForFileChooser(),
      powerStationPage.click(selector),
    ]);

    await fileChooser.accept([
      "/Users/Hymn/Desktop/mywork/ats/src/temp/1707029912126.pdf",
    ]);

    //
    const responseData = await powerStationPage.waitForResponse(
      response =>
        response.url().includes("api/upload/file/upload") &&
        response.status() === 200
    );
    const data = await responseData.json();
    console.log(data.data.id, 444);
  }
};

// 安装设备上传sn 信息
const installSn = async data => {
  const req = await https.request(
    {
      hostname: "csi.feizhisoft.com",
      path: `/finance-owner/external/station/doorInstall/device`,
      method: "POST",
      headers: {
        "csi-token": cookie.value,
        CLIENT: "partner",
        "Content-Type": "application/json",
        "User-Agent":
          "Mozilla/5.0 (iPhone; CPU iPhone OS 17_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.47(0x18002f27) NetType/4G Language/zh_CN",
        Referer:
          "https://servicewechat.com/wxa04f6433818b6f41/0/page-frame.html",
      },
    },
    res => {
      res.setEncoding("utf8");
      console.log("请求成功res---", res.statusCode);
      res.on("data", data => {
        console.log("data的数据----", data);
      });
    }
  );
  // const text =
  //   '--WABoundary+D6CA2DDFF3C6F8D2WA..Content-Disposition: form-data; name="namespace"....finance..--WABoundary+D6CA2DDFF3C6F8D2WA..Content-Disposition: form-data; name="file"; filename="tmp_ec6638a31c9b1157484cf4d457ad432f.jpg"..Content-Type: image/jpeg..........JFIF.....H.H.....XExif..MM.*.................';
  // let data = {
  //   powerStationId: "263781",
  //   self: true,
  //   assemblys: [
  //     "11111111111111",
  //     "33333333333333",
  //     "556666666666666",
  //     "678899999999999",
  //     "567889999998889",
  //     "34678888888899",
  //   ],
  //   inverters: [{ collectorSn: "2455", sn: "13345" }],
  //   installId: 292,
  // };
  const postData = JSON.stringify(data);
  // 设置要发送的内容
  req.write(postData);
  req.on("error", err => {
    console.log("请求失败了err:", err);
  });
  req.end();
};

// 安装设备上传图片
const installUpload = async data => {
  /**
   * file: （二进制）
     namespace: finance
     "multipart/form-data; boundary=WABoundary+D6CA2DDFF3C6F8D2WA",
   */
  const req = await https.request(
    {
      hostname: "csi.feizhisoft.com",
      path: `/upload/file/upload?process=image/resize,w_300,h_300/quality,q_90`,
      method: "POST",
      headers: {
        "csi-token": cookie.value,
        CLIENT: "partner",
        "Content-Type": "multipart/form-data; boundary=WABoundary+D6CA2DDFF3C6F8D2WA",
        "User-Agent":
          "Mozilla/5.0 (iPhone; CPU iPhone OS 17_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.47(0x18002f27) NetType/4G Language/zh_CN",
        Referer:
          "https://servicewechat.com/wxa04f6433818b6f41/0/page-frame.html",
      },
    },
    res => {
      res.setEncoding("utf8");
      console.log("请求成功res---", res.statusCode);
      res.on("data", data => {
        console.log("data的数据----", data);
      });
    }
  );
  // const text =
  //   '--WABoundary+D6CA2DDFF3C6F8D2WA..Content-Disposition: form-data; name="namespace"....finance..--WABoundary+D6CA2DDFF3C6F8D2WA..Content-Disposition: form-data; name="file"; filename="tmp_ec6638a31c9b1157484cf4d457ad432f.jpg"..Content-Type: image/jpeg..........JFIF.....H.H.....XExif..MM.*.................';

  const postData = JSON.stringify(data);
  // 设置要发送的内容
  req.write(postData);
  req.on("error", err => {
    console.log("请求失败了err:", err);
  });
  req.end();
};

// 发生信息授权使用书id
const sendAuthFileId = async (phone, id) => {
  const req = await http.request(
    {
      hostname: "172.16.15.81",
      path: `/api/sync/owner/${phone}/${id}`,
      port: 8081,
      method: "GET",
    },
    res => {
      res.setEncoding("utf8");
      console.log("请求成功res---", res.statusCode);
      res.on("data", data => {
        console.log("data的数据----", data);
      });
    }
  );
  req.on("error", err => {
    console.log("请求失败了err:", err);
  });
  req.end();
};

const sendPhone = async phone => {
  const req = await http.request(
    {
      hostname: "172.16.15.81",
      path: `/api/startFlow/{/${phone}`,
      port: 8081,
      method: "GET",
    },
    res => {
      res.setEncoding("utf8");
      console.log("请求成功res---", res.statusCode);
    }
  );
  req.on("error", err => {
    console.log("请求失败err:", err);
  });
  req.end();
};

// 读取本地文件
const readFile = path => {
  return new Promise((resolve, reject) => {
    fs.readFile(path, "utf-8", (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};

const createDir = async () => {
  //创建文件夹目录
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath);
    console.log("文件夹创建成功");
  } else {
    console.log("文件夹已存在");
  }
};

//
const getUrl = async url => {
  const filePath = "";
  if (typeof url == "string") {
    await downloadFiel(url);
  } else {
    for (let i = 0; i < url.length; i++) {
      await downloadFiel(url[i]);
    }
  }
};

// 下载文件
const downloadFiel = async url => {
  return new Promise(resolve => {
    let imgUrl = url;
    let fileName = new Date().getTime() + ".jpg";
    let stream = fs.createWriteStream(path.join(dirPath, fileName));
    request(imgUrl)
      .pipe(stream)
      .on("data", res => {
        // console.log("文件[" + fileName + "]下载完毕");
      });

    // request({ url: url, encoding: null })
    //   .pipe(stream)
    //   .on("data", function (res) {
    //     resolve(fileName);
    //   });
  });
};

const readDir = async path => {
  return new Promise((resolve, reject) => {
    fs.readdir(path, (err, files) => {
      console.log(err, files);
      if (files.length) {
        resolve(files);
      }
      if (err) {
        fs.mkdirSync(path);
      }
    });
  });
};

console.log(__dirname + "/test.png");

// ------------------------接口区域-------------------------
// // 定义GET请求的路由
// app.get("/api", (req, res) => {
//   res.json({ msg: "success" });
// });

// 业主信息授权
app.post("/api/ownerAuth", (req, res) => {
  console.log(req.body, 111);
  param = req.body;
  openBrowser().then(result => {
    ownerAuth(result);
  });
  res.json({ msg: "success" });
});

// 业主信息补全 编辑
app.post("/api/ownerCompletion", (req, res) => {
  console.log(req.body, 111);
  param = req.body;
  openBrowser().then(result => {
    ownerCompletion(result);
  });
  res.json({ msg: "success" });
});

// 电站列表房屋信息  先 排单-再执行 障碍物不传  提交
app.post("/api/powerstation/house", (req, res) => {
  console.log(req.body, 111);
  param = req.body;
  openBrowser().then(result => {
    house(result);
  });
  res.json({ msg: "success" });
});

// 电站列表设计信息  先 执行-设备信息 新增设备  提交
app.post("/api/powerstation/design", (req, res) => {
  console.log(req.body, 111);
  param = req.body;
  openBrowser().then(result => {
    design(result);
  });
  res.json({ msg: "success" });
});

// 电站设备安装-执行  先执行-安装派单 后执行   提交
app.post("/api/powerstation/install", (req, res) => {
  console.log(req.body, 111);
  param = req.body;
  openBrowser().then(result => {
    install(result);
  });
  res.json({ msg: "success" });
});

// 并网信息
app.post("/api/powerstation/grid", (req, res) => {
  console.log(req.body, 111);
  param = req.body;
  openBrowser().then(result => {
    grid(result);
  });
  res.json({ msg: "success" });
});

// 启动服务器
app.listen(port, () => {
  console.log("Server started on port", port);
});

/**
 * 
 *   // --------------

  var file = "";
  // 创建可读流
  var readerStream = fs.createReadStream("test.png");
  // 设置编码为 utf8。
  readerStream.setEncoding("UTF8");
  // 处理流事件 --> data, end, and error
  readerStream.on("data", function (chunk) {
    file += chunk;
  });
  readerStream.on("end", function () {
    console.log(file);
  });
  readerStream.on("error", function (err) {
    console.log(err.stack);
  });
  console.log("end");

  // ---------

 
  // console.log("data-----------------", req);
  return;
 * 
 */
